<?php

namespace app\controller;
use app\model\BookIntroductionModel;
use app\model\BorrowRecordModel;
use app\model\LibraryBookModel;
use app\model\TmpWriteModel;
use PDO;
use think\annotation\route;
use think\Exception;
use think\facade\Db;
use think\response\Json;

class BookController
{
    /**
     * @route ("addThisBook")
     * @param $book
     * @throws Exception
     */
    public function addThisBook($book, $libraryId, BookIntroductionModel  $bookIntroductionModel, LibraryBookModel $libraryBookModel, TmpWriteModel $tmpWriteModel)
    {

        Db::startTrans();
        try{
            $bookIntroductionModel->addThisBook([
                "introductionId" => $book['introductionId'],
                "bookName" => $book['name'],
                "introduction" => $book['bookContent'],
                "pubicTime" => date("Y-m-d H:i",$book['publishingTime'] / 1000),
                "wordNumber" => $book['wordNumber'],
                "price" => $book['money'],
                "publishHouseName" => $book['publishingHouse'],
                "imgUrl" => $book['imageUrl'],
            ]);
            $libraryBookModel->addThisLibraryBook([
                //id值
                "ISBN" => $book['ISBN'],
                "bookTypeId" => $book['bookType'],
                "introductionId" => $book['introductionId'],
                "libraryId" => $libraryId,
                "classifyId" => $book['midTypeId'],
                "comeTime" => date("Y-m-d")
            ]);
            $now = [];
            foreach ($book['writers'] as $key => $value){
//                echo $value;
                if($value != null && $value['value'] != ""){
                    $tmp = [
                        "ISBN" => $book['ISBN'],
                        "NAME" => $value['value']
                    ];
                    $now[] = $tmp;
                }
            }
//            dump($now);
            $tmpWriteModel->addTmpWrite($now);
        }
        catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            dump($e);
            throw new Exception();
        }
        Db::commit();
    }

    /**
     * @route ("deleteThisLibraryBook")
     * @param $id
     * @return void
     */
    public function deleteThisLibraryBook($id)
    {
        LibraryBookModel::find($id)->delete();
    }

    /**
     * @route ("updateBook")
     * @param $bookNow
     * @return void
     * @throws Exception
     * @throws \Exception
     */
    public function updateBook($book, BookIntroductionModel $bookIntroductionModel, LibraryBookModel  $libraryBookModel)
    {
        Db::startTrans();
        try{
            $bookIntroductionModel::update([
                "introductionId"=>$book['introductionId'],
                "bookName"=>$book['bookName'],
                "wordNumber"=>$book['wordNumber'],
                "price"=>$book['price']
            ]);
            $libraryBookModel::update([
                'ISBN'=>$book['ISBN'],
                'classifyId'=>$book['classifyId'],
                'beBorrowed'=>$book['beBorrowed']
            ]);
        }
        catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            dump($e);
            throw $e;
        }
        Db::commit();
    }

    public function updateThisLibraryBook($book, LibraryBookModel $libraryBookModel)
    {
        $libraryBookModel->updateThisLibraryBook($book);
    }

    /**
     * @route ("borrowThisBook")
     * @param $userId
     * @param $ISBN
     * @return Json
     * @throws Exception
     */
    public function borrowThisBook($borrowId, $userId, $ISBN, BorrowRecordModel $borrowRecordModel)
    {
        $rl = isset($this->testBorrowThisBook($userId, $ISBN)['TRUE']);
//        return  \json($rl);
//        //无法借阅书籍
        if(!$rl){
            throw new Exception("非法操作！");
        }else{
            $this->insertThisBorrowRecord($borrowId, $userId, $ISBN, $borrowRecordModel);
        }
    }

    private function testBorrowThisBook($userId, $ISBN)
    {
        $ret = 0;
//        IN ISBNNow VARCHAR(128),
//        IN userIdNow VARCHAR(128),
//        OUT result BOOL
        $see = Db::query('CALL judgeThisReaderCanBorrowThisBook(:ISBNNow, :userIdNow)',[
            'ISBNNow'=>[&$ISBN,PDO::PARAM_STR],
            'userIdNow'=>[&$userId,PDO::PARAM_STR],
        ]);
        return $see[0][0];
    }

    public function insertThisBorrowRecord($borrowId, $readerId, $ISBN, BorrowRecordModel $borrowRecordModel)
    {
        Db::startTrans();
        //查询借阅记录需要录入的基础信息
        $msg = Db::query("CALL getBorrowBaseMsg(:ISBNNow, :userIdNow)",[
            'ISBNNow'=>[&$ISBN,PDO::PARAM_STR],
            'userIdNow'=>[&$readerId,PDO::PARAM_STR],
        ])[0][0];
//        return json($msg);
        //更改书籍的的借阅状态
        LibraryBookModel::update([
            "ISBN"=>$ISBN,
            "beBorrowed"=>true
        ]);
        //插入借阅信息
       $borrowRecordModel->insertThisBorrowRecord([
           "borrowBegin"=>date("Y-m-d H:i:s"),
           "deadLine"=>date("Y-m-d H:i:s", time() + 86400 * $msg['borrowDays']),
           "borrowId"=>$borrowId,
           "ISBN"=>$ISBN,
           "readerId"=>$readerId
       ]);
       Db::commit();
    }

    /**
     * @route ("returnThisBook")
     * @param $readerId
     * @param $ISBN
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function returnThisBook($readerId, $ISBN, BorrowRecordModel $borrowRecordModel)
    {
        //TODO 当天不能归还
            $borrowRecordModel::where("readerId", $readerId)
                ->where("ISBN", $ISBN)
                ->update([
                "borrowEnd"=>date("Y-m-d H:i:s"),
                ]);
    }

    /**
     * @route ("returnThisBookForAdmin")
     * @param $readerId
     * @param $ISBN
     * @param $desTime
     * @param BorrowRecordModel $borrowRecordModel
     * @return void
     */
    public function returnThisBookForAdmin($readerId, $ISBN, $desTime, BorrowRecordModel $borrowRecordModel)
    {
        //TODO 当天不能归还
        $borrowRecordModel::where("readerId", $readerId)
            ->where("ISBN", $ISBN)
            ->update([
                "borrowEnd"=>$desTime,
            ]);
    }

}